package com.aiti.lulian.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.page.PageInfo;
import com.aiti.base.core.page.PageResult;
import com.aiti.base.core.utils.message.Message;
import com.aiti.framework.commons.dictmodel.entity.SysDictData;
import com.aiti.framework.commons.dictmodel.mapper.SysDictDataMapper;
import com.aiti.lulian.dto.*;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.entity.excel.ProductImport;
import com.aiti.lulian.entity.newCard.ShowEnterpriseTrial;
import com.aiti.lulian.feign.ScaleEnterpriseService;
import com.aiti.lulian.mapper.*;
import com.aiti.lulian.mapper.newCard.ShowEnterpriseTrialMapper;
import com.aiti.lulian.service.*;
import com.aiti.lulian.vo.*;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * description:
 * auth fcb
 * date 2025-04-28 16:31
 **/
@Service
@Slf4j
public class Product0428ServiceImpl extends BaseSerivceImpl<Product0428Mapper, Product0428> implements Product0428Service {

    @Autowired
    private ProductSalesMapper productSalesMapper;
    @Autowired
    private LuLianEnterpriseUserMapper enterpriseUserMapper;
    @Autowired
    private LuLianEnterpriseMapper luLianEnterpriseMapper;
    @Autowired
    private IProductAttributeService attributeService;
    @Autowired
    private EnterpriseProductParamService productParamService;
    @Autowired
    private ISysAttachmentService sysAttachmentService;
    @Autowired
    private IProductDetailedService productDetailedService;
    @Autowired
    private LuLianEnterpriseHistoryMapper luLianEnterpriseHistoryMapper;
    @Autowired
    private SysAreaMapper sysAreaMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private ScaleEnterpriseService scaleEnterpriseService;
    @Autowired
    private ShowEnterpriseTrialMapper showEnterpriseTrialMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveProductInfo(Product0428ParamDto dto, String userId) {
        // 1. 校验参数
        this.checkSaveParam(dto);
        // 2. 校验企业与用户的绑定，校验企业是否上线
        this.checkUserEnterprise(dto, userId);
        // 3. 保存商品
        String baseId = IdUtil.fastUUID();
        Product0428 product = this.getProductPo(dto, userId, baseId);
        this.baseMapper.insert(product);
        // 4. 保存单位
        this.saveOrUpdateUnit(dto, baseId, false);
        // 5. 保存属性和参数。属性还是原来的表
        this.saveOrUpdateAttributeAndParam(dto.getProductParamList(), baseId, false);
        // 6. 保存图片
        this.saveOrUpdatePic(dto.getAttachments(), baseId, false);
        // 7. 保存长图
        this.saveOrUpdateDetail(dto.getBaseIntroduction(), baseId);
        // 8. 保存到产品库
        this.saveProductToSearch(dto, product);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateProductInfo(Product0428ParamDto dto, String userId) {
        // 1. 校验参数
        this.checkUpdateParam(dto);
        // 2. 校验企业与用户的绑定，校验企业是否上线
        this.checkUserEnterprise(dto, userId);
        // 3. 保存商品
        Product0428 product = this.getUpdateProductPo(dto);
        String baseId = product.getBaseId();
        this.baseMapper.updateById(product);
        // 4. 保存单位
        this.saveOrUpdateUnit(dto, baseId, true);
        // 5. 保存属性和参数。属性还是原来的表
        this.saveOrUpdateAttributeAndParam(dto.getProductParamList(), baseId, true);
        // 6. 保存图片
        this.saveOrUpdatePic(dto.getAttachments(), baseId, true);
        // 7. 保存长图
        this.saveOrUpdateDetail(dto.getBaseIntroduction(), baseId);
        // 8. 保存到产品库
        this.saveProductToSearch(dto, product);
    }

    @Override
    public void updateVisibleBatch(Product0428ParamDto dto, String userId) {
        List<String> baseIds = dto.getBaseIds();
        this.update(new LambdaUpdateWrapper<Product0428>().in(Product0428::getBaseId, baseIds).set(Product0428::getIsVisible, dto.getIsVisible()));
    }

    @Override
    public ProductInfo0428Vo getProductInfo(String baseId) {
        if(StrUtil.isEmpty(baseId)) {
            throw new BusinessException("商品id不能为空");
        }
        ProductInfo0428Vo productInfoVo = new ProductInfo0428Vo();
        Product0428 product = this.baseMapper.selectById(baseId);
        if(product == null) {
            throw new BusinessException("未查询到商品信息");
        }
        BeanUtil.copyProperties(product,productInfoVo);
        BigDecimal price = product.getPrice();
        if(price != null && price.compareTo(new BigDecimal(0)) != 0){
            productInfoVo.setBaseNote(price.toPlainString());
        }
        //查询产品属性
        List<ProductAttribute> attributes = attributeService.list(new QueryWrapper<ProductAttribute>().eq("product_id", baseId).orderByAsc("sort"));
        List<ProductParamVo> productParamVoList = this.getProductParamVos(baseId, attributes);
        if (productParamVoList.isEmpty()) {
            productParamVoList = new ArrayList<>();
        }
        productInfoVo.setProductParamList(productParamVoList);
        // 设置品牌。旧数据的品牌在原来的属性里面，如果产品表的bran字段是空就去属性里面找品牌。
        // 如果此时更新，则之前的属性会被删除重新插入，品牌则进入产品表里面

        if(StrUtil.isEmpty(product.getBrand())) {
            for(ProductAttribute attribute : attributes) {
                if("品牌".equals(attribute.getBaseName())) {
                    productInfoVo.setBrand(attribute.getBaseValue());
                    break;
                }
            }
        }
        // 查询图片
        List<SysAttachment> pics = sysAttachmentService.list(new QueryWrapper<SysAttachment>().eq("rel_id", product.getBaseId()).orderByAsc("sort"));
        productInfoVo.setAttachments(pics);
        // 查询单位
        ProductSales sales = productSalesMapper.selectOne(new QueryWrapper<ProductSales>().eq("product_id", product.getBaseId()));
        if(sales != null){
            productInfoVo.setUnit(sales.getUnit());
        }
        return productInfoVo;
    }

    @Override
    public PageResult<ProductPageVo> productPageList(ProductQueryParamDto dto) {
        if(StrUtil.isEmpty(dto.getEnterpriseId())) {
            throw new BusinessException("企业id不能为空");
        }
        Page<ProductPageVo> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        List<ProductPageVo> list = this.baseMapper.productPageList(page, dto);
        if(CollectionUtil.isNotEmpty(list)) {
            for(ProductPageVo vo : list) {
                // 品牌
                if(StrUtil.isEmpty(vo.getBrand())) {
                    List<String> brands = this.baseMapper.queryProductBrand(vo.getBaseId());
                    if(CollectionUtil.isNotEmpty(brands)) {
                        vo.setBrand(String.join(",", brands));
                    }
                }
                // 参数和单位
                List<EnterpriseProductParam> enterpriseProductParams = this.baseMapper.queryProductParamByProductId(vo.getBaseId());
                if(CollectionUtil.isNotEmpty(enterpriseProductParams)) {
                    List<String> modelList = enterpriseProductParams.stream().map(EnterpriseProductParam::getModel).filter(StringUtils::isNotBlank).collect(Collectors.toList());
                    vo.setModel(String.join(",", modelList));
                }
                // 产品图片：默认选取第一张
                List<SysAttachment> picList = sysAttachmentService.list(new QueryWrapper<SysAttachment>().eq("rel_id", vo.getBaseId()).eq("category", "pic").orderByAsc("sort"));
                if (CollectionUtil.isNotEmpty(picList)) {
                    vo.setPic(picList.get(0).getFullPath());
                }
            }
        }
        return new PageResult<>(list, new PageInfo(dto.getPageNum(), dto.getPageSize()), page.getTotal());
    }

    private List<ProductParamVo> getProductParamVos(String baseId, List<ProductAttribute> attributes) {
        List<EnterpriseProductParam> paramList = productParamService.list(new QueryWrapper<EnterpriseProductParam>().eq("product_id", baseId));
        List<ProductParamVo> productParamVoList = new ArrayList<>(10);
        if(CollectionUtil.isNotEmpty(paramList)) {
            for (EnterpriseProductParam param : paramList) {
                ProductParamVo paramVo = new ProductParamVo();
                List<ProductParamAttributeDto> attributeList = new ArrayList<>(10);
                paramVo.setAttributeList(attributeList);
                paramVo.setProductId(param.getProductId());
                paramVo.setModel(param.getModel());

                if(param.getModelPrice() != null) {
                    paramVo.setModelPrice(param.getModelPrice().toPlainString());
                }else {
                    paramVo.setModelPrice("");
                }
                if(CollectionUtil.isEmpty(attributes)) {
                    continue;
                }
                // 查询属性
                for (ProductAttribute attribute : attributes) {
                    if(param.getBaseId().equals(attribute.getParamId())) {
                        ProductParamAttributeDto attributeDto = new ProductParamAttributeDto();
                        attributeDto.setBaseName(attribute.getBaseName());
                        attributeDto.setBaseValue(attribute.getBaseValue());
                        attributeList.add(attributeDto);
                    }
                }
                productParamVoList.add(paramVo);
            }
        }
        // 兼容属性
        else {
            ProductParamVo paramVo = new ProductParamVo();
            List<ProductParamAttributeDto> attributeList = new ArrayList<>(10);
            paramVo.setAttributeList(attributeList);
            for(ProductAttribute attribute : attributes) {
                ProductParamAttributeDto attributeDto = new ProductParamAttributeDto();
                attributeDto.setBaseName(attribute.getBaseName());
                attributeDto.setBaseValue(attribute.getBaseValue());
                attributeList.add(attributeDto);
            }
            if (CollectionUtil.isEmpty(attributeList)) {
                return productParamVoList;
            }
            productParamVoList.add(paramVo);
        }
        return productParamVoList;
    }

    private void saveProductToSearch(Product0428ParamDto dto, Product0428 product) {
//        LuLianEnterpriseHistory luLianEnterpriseHistory = luLianEnterpriseHistoryMapper.selectById(product.getEnterpriseId());
        String province, city, county;
        LuLianEnterprise luLianEnterpriseHistory = luLianEnterpriseMapper.selectById(product.getEnterpriseId());
        if (luLianEnterpriseHistory != null){
            province = luLianEnterpriseHistory.getProvince();
            city = luLianEnterpriseHistory.getCity();
            county = luLianEnterpriseHistory.getCounty();
        } else {
            ShowEnterpriseTrial showEnterpriseTrial = showEnterpriseTrialMapper.selectById(product.getEnterpriseId());
            if (showEnterpriseTrial == null) {
                throw new BusinessException("没有找到企业信息");
            }
            province = showEnterpriseTrial.getProvince();
            city = showEnterpriseTrial.getCity();
            county = showEnterpriseTrial.getCounty();
        }
        List<SysArea> sysAreas = sysAreaMapper.selectList(new QueryWrapper<SysArea>().in("base_id", province, county, city));
        //查询行业
        SysDictData sysDictData = sysDictDataMapper.selectById(dto.getOneLevelIndustry());
        if((dto.getFlag() == null || dto.getFlag() != 1) && CollectionUtil.isEmpty(sysAreas)){
            throw new BusinessException("请设置该企业的省市区");
        }
        //保存产品到Search库
        ScaleSearchProductDto searchProductDto = ScaleSearchProductDto.builder()
                .baseId(product.getBaseId())
                .isScale("0")
                .baseName(product.getBaseName())
                .price(dto.getBaseNote())
                .build();

        if(sysDictData != null){
            searchProductDto.setIndustry(sysDictData.getBaseName());
        }

        //设置省市区
        if (CollectionUtil.isNotEmpty(sysAreas)) {
            Map<String, String> areaMap = sysAreas.stream().collect(Collectors.toMap(SysArea::getBaseId, SysArea::getBaseName));
            if(areaMap.containsKey(province)){
                searchProductDto.setProvince(areaMap.get(province));
            }
            if(areaMap.containsKey(city)){
                searchProductDto.setCity(areaMap.get(city));
            }

            if(areaMap.containsKey(county)){
                searchProductDto.setCounty(areaMap.get(county));
            }
        }

        //设置图片
        List<SysAttachmentDto> attachments = dto.getAttachments();
        if(CollectionUtil.isNotEmpty(attachments)){
            List<SysAttachmentDto> pic = attachments.stream().filter(k -> StringUtils.equals(k.getCategory(), "pic")).collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(pic)){
                searchProductDto.setPic(pic.get(0).getFullPath());
            }else{
                SysAttachmentDto sysAttachmentDto = attachments.get(0);
                searchProductDto.setPic(sysAttachmentDto.getFullPath());
            }
        }
        Message message = scaleEnterpriseService.addSearchProduct(searchProductDto);
        if(message.getCode() == 1){
            throw new BusinessException("保存产品到搜索库失败");
        }
    }

    private void saveOrUpdateDetail(String baseIntroduction, String productId) {
        ProductDetailed productDetailed = productDetailedService.getOne(new QueryWrapper<ProductDetailed>().eq("product_id", productId));
        if(productDetailed == null){
            productDetailed = new ProductDetailed();
            productDetailed.setBaseId(IdUtil.simpleUUID());
            productDetailed.setProductId(productId);
            productDetailed.setContent(baseIntroduction);
            productDetailedService.save(productDetailed);
        }else{
            productDetailed.setContent(baseIntroduction);
            productDetailedService.updateById(productDetailed);
        }

    }

    private void saveOrUpdatePic(List<SysAttachmentDto> attachments, String productId, boolean isUpdate) {
        if(CollectionUtil.isEmpty(attachments)) {
            return;
        }
        if(isUpdate) {
            sysAttachmentService.remove(new QueryWrapper<SysAttachment>().eq("rel_id", productId));
        }
        int i = 0;
        for(SysAttachmentDto attachment : attachments){
            attachment.setBaseId(IdUtil.simpleUUID());
            attachment.setRelId(productId);
            if(i == 0){
                attachment.setCategory("pic");
            }else{
                attachment.setCategory("other");
            }
            i++;
        }
        List<SysAttachment> sysAttachments = BeanUtil.copyToList(attachments, SysAttachment.class);
        if(!sysAttachments.isEmpty()) {
            sysAttachmentService.saveBatch(sysAttachments);
        }
    }

    /**
     * 保存属性和参数
     * 不管属性没有还是参数没有，都要保存。
     * @param productParamList
     * @param productId
     * @param isUpdate
     */
    private void saveOrUpdateAttributeAndParam(List<ProductParamDto> productParamList, String productId, boolean isUpdate) {
        if(CollectionUtil.isEmpty(productParamList)) {
            return;
        }
        if(isUpdate) {
            productParamService.remove(new QueryWrapper<EnterpriseProductParam>().eq("product_id", productId));
            attributeService.remove(new QueryWrapper<ProductAttribute>().eq("product_id", productId));
        }
        List<EnterpriseProductParam> paramList = new ArrayList<>(10);
        List<ProductAttribute> attributeList = new ArrayList<>(10);
        for(ProductParamDto item : productParamList) {
            String paramId = IdUtil.fastUUID();
            EnterpriseProductParam param = new EnterpriseProductParam();
            param.setBaseId(paramId);
            param.setProductId(productId);
            param.setModel(item.getModel());
            param.setModelPrice(item.getModelPrice());
            paramList.add(param);

            if(CollectionUtil.isNotEmpty(item.getAttributeList())) {
                for(ProductParamAttributeDto attributeDto : item.getAttributeList()) {
                    ProductAttribute attribute = new ProductAttribute();
                    attribute.setBaseId(IdUtil.fastUUID());
                    attribute.setProductId(productId);
                    attribute.setBaseName(attributeDto.getBaseName());
                    attribute.setBaseValue(attributeDto.getBaseValue());
                    attribute.setParamId(paramId);
                    attribute.setSort(attributeDto.getSort());
                    attributeList.add(attribute);
                }

            }
        }

        if(!attributeList.isEmpty()) {
            attributeService.saveBatch(attributeList);
        }
        if(!paramList.isEmpty()) {
            productParamService.saveBatch(paramList);
        }
    }

    @Override
    public PageResult<Product0428ListVo> productPage(Page page, Product0428ParamListDto dto) {
        List<Product0428ListVo> list = this.getBaseMapper().productList(page, dto);
        return new PageResult<>(list, new PageInfo(dto.getPageNum(), dto.getPageSize()), page.getTotal());
    }

    @Override
    public PageResult<Product0428ListVo> productPageNew(Page page, Product0428ParamListDto dto) {
        List<Product0428ListVo> list = this.getBaseMapper().productListNew(page, dto);
        return new PageResult<>(list, new PageInfo(dto.getPageNum(), dto.getPageSize()), page.getTotal());
    }

    @Override
    public Product0428DetailVo productDetail(String productId, String paramId) {
        Product0428 product = this.getById(productId);
        Product0428DetailVo product0428DetailVo = new Product0428DetailVo();
        if(product != null) {
            BeanUtil.copyProperties(product, product0428DetailVo);
            List<ProductAttribute> attributeList = attributeService.list(new LambdaQueryWrapper<ProductAttribute>().eq(ProductAttribute::getParamId, paramId).eq(ProductAttribute::getProductId, productId).orderByAsc(ProductAttribute::getSort));
            product0428DetailVo.setAttributeList(attributeList);
            List<EnterpriseProductParam> paramList = productParamService.list(new LambdaQueryWrapper<EnterpriseProductParam>().eq(EnterpriseProductParam::getProductId, productId));
            product0428DetailVo.setParamList(paramList);
            List<SysAttachment> attachmentList = sysAttachmentService.list(new LambdaQueryWrapper<SysAttachment>().eq(SysAttachment::getRelId, productId).orderByAsc(SysAttachment::getSort));
            product0428DetailVo.setAttachmentList(attachmentList);
            List<ProductAttribute> oldAttrList = attributeService.list(new LambdaQueryWrapper<ProductAttribute>().eq(ProductAttribute::getProductId, productId).orderByAsc(ProductAttribute::getSort));
            product0428DetailVo.setOldAttributeList(oldAttrList);
        }
        return product0428DetailVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProductSort(ProductSortDto dto) {
       this.baseMapper.updateProductSort(dto);
    }

    private void checkUserEnterprise(Product0428ParamDto dto, String userId) {
        List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserMapper.selectList(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
        if (CollectionUtil.isEmpty(enterpriseUserList)) {
            throw new BusinessException("当前用户未绑定企业");
        }
//        if(enterpriseUserList.size() != 1){
//            throw new BusinessException("用户和企业绑定关系异常");
//        }
        boolean isExist = enterpriseUserList.stream().anyMatch(i -> i.getEnterpriseId().equals(dto.getEnterpriseId()));
        if (!isExist) {
            throw new BusinessException("当前用户绑定企业与参数企业不一致");
        }
        LuLianEnterprise enterprise = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().eq("base_id", dto.getEnterpriseId()).eq("is_delete", "0"));
        if (enterprise == null) {
            // 去查询试用企业表中是否存在企业数据，若存在，则表示当前是试用企业用户在进行业务操作
            ShowEnterpriseTrial trial = showEnterpriseTrialMapper.selectOne(new QueryWrapper<ShowEnterpriseTrial>().eq("base_id", dto.getEnterpriseId()).eq("is_delete", "0"));
            if (trial == null) {
                throw new BusinessException("该企业没有填写企业上线资料");
            }
        }
    }

    private void saveOrUpdateUnit(Product0428ParamDto dto, String productId, boolean isUpdate) {
        if(isUpdate) {
            productSalesMapper.delete(new QueryWrapper<ProductSales>().eq("product_id", productId));
        }
        ProductSales sales = ProductSales.builder()
                .baseId(IdUtil.simpleUUID())
                .productId(productId)
                .unit(dto.getUnit())
                .build();
        productSalesMapper.insert(sales);
    }

    private Product0428 getProductPo(Product0428ParamDto dto, String userId, String baseId) {
        Product0428 product = new Product0428();
        BeanUtil.copyProperties(dto, product);
        product.setBaseId(baseId);
        product.setStatus("1");
        if(NumberUtil.isNumber(dto.getBaseNote())){
            product.setPrice(new BigDecimal(dto.getBaseNote()));
            product.setBaseNote("");
        }
        product.setCreator(userId);
        product.setBaseCreateTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        product.setBaseUpdateTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        // 排序字段
        if (product.getSort() == null) {
            List<Product0428> list = this.list(new LambdaQueryWrapper<Product0428>().eq(Product0428::getEnterpriseId, dto.getEnterpriseId()).eq(Product0428::getIsDelete, 0).orderByDesc(Product0428::getSort));
            if (list.isEmpty()) {
                product.setSort(1);
            } else {
                product.setSort(list.get(0).getSort() + 1);
            }
        }
        return product;
    }

    private Product0428 getUpdateProductPo(Product0428ParamDto dto) {
        Product0428 product = new Product0428();
        BeanUtil.copyProperties(dto,product);
        if(NumberUtil.isNumber(dto.getBaseNote())){
            product.setPrice(new BigDecimal(dto.getBaseNote()));
            dto.setBaseNote(null);
            product.setBaseNote(null);
        }else{
            product.setPrice(null);
        }
        product.setBaseUpdateTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        return product;
    }

    private void checkSaveParam(Product0428ParamDto dto) {
        if(StrUtil.isEmpty(dto.getEnterpriseId())) {
            throw new BusinessException("企业id不能为空");
        }
    }

    private void checkUpdateParam(Product0428ParamDto dto) {
        if(StrUtil.isEmpty(dto.getEnterpriseId())) {
            throw new BusinessException("企业id不能为空");
        }
        if(StrUtil.isEmpty(dto.getBaseId())) {
            throw new BusinessException("产品id不能为空");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message importBatch(MultipartFile file, String userId, String enterpriseId) throws IOException {
        // 构建报错信息集
        List<String> msgList = new ArrayList<>();
        // 读取数据
        List<ProductImport> productImportList = EasyExcel.read(file.getInputStream()).head(ProductImport.class).headRowNumber(1).sheet("产品").doReadSync();
        if (productImportList == null) {
            return Message.fail("请正确上传文件");
        }
        if (productImportList.isEmpty()) {
            return Message.fail("尚未读取到数据");
        }
        List<Product0428> product0428s = new ArrayList<>();
        if (StrUtil.isBlank(enterpriseId)) {
            return Message.fail("企业信息无效");
        }
        // 循环前保存一个初始顺序
        int sortVal;
        List<Product0428> list = this.list(new LambdaQueryWrapper<Product0428>().eq(Product0428::getEnterpriseId, enterpriseId).eq(Product0428::getIsDelete, 0).orderByDesc(Product0428::getSort));
        if (list.isEmpty()) {
            sortVal = 1;
        } else {
            sortVal = list.get(0).getSort() + 1;
        }
        for (ProductImport productImport : productImportList) {
            if (StrUtil.isBlank(productImport.getBaseName())) {
                msgList.add("第" + (productImportList.indexOf(productImport) + 1) + "条：产品名称-不能为空<br/>");
                continue;
            }
            if (StrUtil.isBlank(productImport.getOneLevelIndustry())) {
                msgList.add("第" + (productImportList.indexOf(productImport) + 1) + "条：所属行业一类-不能为空<br/>");
                continue;
            }
            if (StrUtil.isBlank(productImport.getTowLevelIndustry())) {
                msgList.add("第" + (productImportList.indexOf(productImport) + 1) + "条：所属行业二类-不能为空<br/>");
                continue;
            }
            if (StrUtil.isBlank(productImport.getIsNegotiable())) {
                msgList.add("第" + (productImportList.indexOf(productImport) + 1) + "条：价格是否面议-不能为空<br/>");
                continue;
            }
            if (StrUtil.isBlank(productImport.getLinkMan())) {
                msgList.add("第" + (productImportList.indexOf(productImport) + 1) + "条：联系人-不能为空<br/>");
                continue;
            }
            if (StrUtil.isBlank(productImport.getLinkPhone())) {
                msgList.add("第" + (productImportList.indexOf(productImport) + 1) + "条：联系电话-不能为空<br/>");
                continue;
            }
            Product0428 product = new Product0428();
            // 产品名称
            product.setBaseName(productImport.getBaseName());
            // 所属行业一类
            SysDictData sysDictDataOne = sysDictDataMapper.selectOne(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getBaseName, productImport.getOneLevelIndustry()).eq(SysDictData::getDictTypeNo, "ENTERPRISE_INDUSTRY").eq(SysDictData::getBaseParentId, "0").eq(SysDictData::getIsDelete, false).eq(SysDictData::getStatus, "0"));
            if (sysDictDataOne == null) {
                msgList.add("第" + (productImportList.indexOf(productImport) + 1) + "条：所属行业一类-类型不存在<br/>");
                continue;
            }
            product.setOneLevelIndustry(sysDictDataOne.getBaseId());
            // 所属行业二类
            SysDictData sysDictDataTwo = sysDictDataMapper.selectOne(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getBaseName, productImport.getTowLevelIndustry()).eq(SysDictData::getBaseParentId, sysDictDataOne.getBaseId()).eq(SysDictData::getIsDelete, false).eq(SysDictData::getStatus, "0"));
            if (sysDictDataTwo == null) {
                msgList.add("第" + (productImportList.indexOf(productImport) + 1) + "条：所属行业二类-类型不存在<br/>");
                continue;
            }
            product.setTowLevelIndustry(sysDictDataTwo.getBaseId());
            // 品牌
            product.setBrand(productImport.getBrand());
            // 价格是否面议
            if (!("是".equals(productImport.getIsNegotiable()) || "否".equals(productImport.getIsNegotiable()))) {
                msgList.add("第" + (productImportList.indexOf(productImport) + 1) + "条：价格是否面议-内容填写无效<br/>");
                continue;
            }
            if ("是".equals(productImport.getIsNegotiable())) {
                product.setBaseNote("面议");
            } else {
                // 自定义价格
                if (StrUtil.isBlank(productImport.getPrice())) {
                    msgList.add("第" + (productImportList.indexOf(productImport) + 1) + "条：该条为非面议产品，自定义价格-不能为空<br/>");
                    continue;
                }
                if (!NumberUtil.isNumber(productImport.getPrice())) {
                    msgList.add("第" + (productImportList.indexOf(productImport) + 1) + "条：该条为非面议产品，自定义价格-价格填写无效<br/>");
                    continue;
                }
                product.setPrice(new BigDecimal(productImport.getPrice()));
                product.setBaseNote("");
            }
            // 联系人
            product.setLinkMan(productImport.getLinkMan());
            // 联系电话格式的校验
//            if (!productImport.getLinkPhone().matches("^(1[3-9]\\d{9}|0[1-9]\\d{1,2}-\\d{7,8}(-\\d+)?)$")) {
            String linkPhone = productImport.getLinkPhone();
            if (!(linkPhone.matches("^(?:(?:\\+|00)86)?1[3-9]\\d{9}$") // 国内11位手机号码
                    || linkPhone.matches("^(?:(?:0\\d{2,3}-)?\\d{7,8})(?:-\\d{1,6})?$") // 国内固话
                    || linkPhone.matches("^400[-]?\\d{3}[-]?\\d{4}$"))) { // 虚拟号码（全国统一接入码服务）400-xxx-xxxx
                msgList.add("第" + (productImportList.indexOf(productImport) + 1) + "条：联系电话-号码填写无效<br/>");
                continue;
            }
            product.setLinkPhone(productImport.getLinkPhone());
            product.setBaseId(IdUtil.fastUUID());
            product.setEnterpriseId(enterpriseId);
            product.setSort(sortVal++);
            product.setCreator(userId);
            product.setBaseCreateTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            product0428s.add(product);
        }
        if (product0428s.size() > 0) {
            this.saveBatch(product0428s);
        }
        if (msgList.size() > 0) {
            return Message.fail("以下数据导入失败：<br/>" + msgList.stream().collect(Collectors.joining("")));
        } else {
            return Message.success("导入成功");
        }
    }

    @Override
    public List<ProductPageVo> productRecommendation(String enterpriseId) {
        ProductQueryParamDto dto = new ProductQueryParamDto();
        dto.setEnterpriseId(enterpriseId);
        List<ProductPageVo> list = this.baseMapper.productPageList(null, dto);
        List<ProductPageVo> randomThreeElement = getRandomThreeElement(list);
        if (CollectionUtil.isNotEmpty(randomThreeElement)) {
            for(ProductPageVo vo : randomThreeElement) {
                // 产品图片：默认选取第一张
                List<SysAttachment> picList = sysAttachmentService.list(new QueryWrapper<SysAttachment>().eq("rel_id", vo.getBaseId()).eq("category", "pic").orderByAsc("sort"));
                if (CollectionUtil.isNotEmpty(picList)) {
                    vo.setPic(picList.get(0).getFullPath());
                }
            }
        }
        return randomThreeElement;
    }

    /**
     * 获取某一list对象中随机的三个元素
     */
    private List<ProductPageVo> getRandomThreeElement(List<ProductPageVo> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            return Collections.emptyList();
        }
        List<ProductPageVo> copy = new ArrayList<>(dataList);
        Collections.shuffle(copy);
        int take = Math.min(3, copy.size());
        return new ArrayList<>(copy.subList(0, take));
    }
}
